package com.ruoyi.eims.cgreturn.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.base.api.AccountService;
import com.ruoyi.base.api.InventoryService;
import com.ruoyi.base.api.domain.Account;
import com.ruoyi.base.api.domain.Inventory;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.eims.cgreturn.domain.CgreturnOrder;
import com.ruoyi.eims.cgreturn.domain.CgreturnPay;
import com.ruoyi.eims.cgreturn.dto.CgDto;
import com.ruoyi.eims.cgreturn.mapper.CgreturnOrderMapper;
import com.ruoyi.eims.cgreturn.mapper.CgreturnPayMapper;
import com.ruoyi.eims.cgreturn.service.ICgreturnOrderService;
import com.ruoyi.eims.purchase.domain.PurchaseOrder;
import com.ruoyi.eims.purchase.domain.PurchaseOrderDetails;
import com.ruoyi.eims.purchase.mapper.PurchaseOrderDetailsMapper;
import com.ruoyi.eims.purchase.mapper.PurchaseOrderMapper;
import com.ruoyi.eims.store.domain.InboundOrder;
import com.ruoyi.eims.store.domain.InboundOrderDetails;
import com.ruoyi.eims.store.mapper.InboundOrderDetailsMapper;
import com.ruoyi.eims.store.mapper.InboundOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 退款管理Service业务层处理
 * 
 * @author hp
 * @date 2023-02-06
 */
@Service
public class CgreturnOrderServiceImpl implements ICgreturnOrderService 
{
    @Autowired
    private CgreturnOrderMapper cgreturnOrderMapper;

    @Autowired
    private CgreturnPayMapper cgreturnPayMapper;
    @Autowired
    private AccountService accountService;
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private PurchaseOrderDetailsMapper purchaseOrderDetailsMapper;
    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private InboundOrderMapper inboundOrderMapper;

    @Autowired
    private InboundOrderDetailsMapper inboundOrderDetailsMapper;

    /**
     * 查询退款管理
     * 
     * @param id 退款管理主键
     * @return 退款管理
     */
    @Override
    public CgreturnOrder selectCgreturnOrderById(Long id)
    {
        return cgreturnOrderMapper.selectCgreturnOrderById(id);
    }

    /**
     * 查询退款管理列表
     * 
     * @param cgreturnOrder 退款管理
     * @return 退款管理
     */
    @Override
    public List<CgreturnOrder> selectCgreturnOrderList(CgreturnOrder cgreturnOrder)
    {
        return cgreturnOrderMapper.selectCgreturnOrderList(cgreturnOrder);
    }

    /**
     * 新增退款管理
     * 
     * @param cgDto 退款管理
     * @return 结果
     */
    @Override
    public int insertCgreturnOrder(CgDto cgDto)
    {
        if (cgDto.getWarehouseId() == null) {
            throw new RuntimeException("仓库不能为空");
        }

        List<PurchaseOrder> list = cgDto.getSelectCgorderList();
        String collect = list.stream().map(PurchaseOrder::getGoodsId).collect(Collectors.joining(","));
        String goodsId = String.join(",", Arrays.stream(collect.split(",")).collect(Collectors.toSet()));




        CgreturnOrder order = new CgreturnOrder();
        order.setCreateDate(new Date());
        order.setPid(cgDto.getAccountId());
        //order.setGoodsId();
        order.setRelPay(cgDto.getPayamount());
        order.setOrderNo(list.stream().map(PurchaseOrder::getOrderNo).collect(Collectors.joining(",")));
        //order.setPid();
        //order.setPrice(cgDto.getTotalAmount().subtract(cgDto.getDepositAmount()).subtract(cgDto.getDiscountAmount()));
        //order.setShouldPay(order.getPrice().subtract(cgDto.getPayamount()));
        order.setRePay(cgDto.getTotalAmount());
        order.setGoodsId(goodsId);
        order.setState(cgDto.getState());
        order.setUserId(SecurityUtils.getUserId());
        order.setVendorId(list.stream().map(t->String.valueOf(t.getVendorId())).distinct().collect(Collectors.joining(",")));
        order.setVendorName(String.join(",", Arrays.stream(cgDto.getVendorName()).collect(Collectors.toSet())));
        order.setShouldPay(cgDto.getTotalAmount().subtract(cgDto.getDiscountAmount()));
        int i = cgreturnOrderMapper.insertCgreturnOrder(order);

        //审核通过账号退款
        /*if (cgDto.getState() == 1) {
            AjaxResult result = accountService.getInfo(cgDto.getAccountId());

            Object o = result.get(AjaxResult.DATA_TAG);
            String s = JSONObject.toJSONString(o);
            //账号
            Account account = JSONObject.parseObject(s, Account.class);

            //退款
            account.setCurrentBalance(account.getCurrentBalance().add(cgDto.getPayamount()));
            accountService.edit(account);


            //生成订单
            CgreturnPay pay = new CgreturnPay();
            pay.setAccountId(cgDto.getAccountId());
            pay.setCreatedate(new Date());
            pay.setInboundOrderId(order.getId());
            pay.setNote("退款支付单");
            pay.setPrice(cgDto.getPayamount());
            pay.setOrderno(order.getOrderNo());
            cgreturnPayMapper.insertCgreturnPay(pay);

            //减库存
            String orderNos = order.getOrderNo();
            String[] split = orderNos.split(",");
            Inventory inventory = new Inventory();
            for (String orderNo : Arrays.stream(split).collect(Collectors.toList())) {
                PurchaseOrder purchaseOrder = purchaseOrderMapper.selectPurchaseOrderByOrderNo(orderNo);
                List<PurchaseOrderDetails>  purchaseOrderDetails = purchaseOrderDetailsMapper.selectPurchaseOrderDetailsByOrderId(purchaseOrder.getId());

                for (PurchaseOrderDetails detail : purchaseOrderDetails) {
                    inventory.setWarehouseId(cgDto.getWarehouseId());
                    //inventory.setCategory();
                    inventory.setGoodsId(detail.getGoodsId());
                    inventory.setInventory(String.valueOf(detail.getCount()));
                    inventory.setState(1);
                    inventory.setPrice(detail.getPrice());
                    inventoryService.save(inventory);
                }

            }
        }*/

        if (cgDto.getState() == 1) {
            shenghe(order);
        }


        //return cgreturnOrderMapper.insertCgreturnOrder(cgDto);
        return i;
    }

    /**
     * 修改退款管理
     * 
     * @param cgreturnOrder 退款管理
     * @return 结果
     */
    @Override
    public int updateCgreturnOrder(CgreturnOrder cgreturnOrder)
    {
        return cgreturnOrderMapper.updateCgreturnOrder(cgreturnOrder);
    }

    /**
     * 批量删除退款管理
     * 
     * @param ids 需要删除的退款管理主键
     * @return 结果
     */
    @Override
    public int deleteCgreturnOrderByIds(Long[] ids)
    {
        return cgreturnOrderMapper.deleteCgreturnOrderByIds(ids);
    }

    /**
     * 删除退款管理信息
     * 
     * @param id 退款管理主键
     * @return 结果
     */
    @Override
    public int deleteCgreturnOrderById(Long id)
    {
        return cgreturnOrderMapper.deleteCgreturnOrderById(id);
    }

    @Override
    public int shenghe(CgreturnOrder cgreturnOrder) {

        cgreturnOrder.setState(1);

        //减库存
        String orderNos = cgreturnOrder.getOrderNo();
        String[] split = orderNos.split(",");
        Inventory inventory = new Inventory();
        InboundOrder inboundOrder = new InboundOrder();
        InboundOrderDetails details = new InboundOrderDetails();
        for (String orderNo : Arrays.stream(split).collect(Collectors.toList())) {
            PurchaseOrder purchaseOrder = purchaseOrderMapper.selectPurchaseOrderByOrderNo(orderNo);
            List<PurchaseOrderDetails>  purchaseOrderDetails = purchaseOrderDetailsMapper.selectPurchaseOrderDetailsByOrderId(purchaseOrder.getId());

            purchaseOrder.setState(4);

            inboundOrder.setOrderNo(orderNo);
            List<InboundOrder> inboundOrders = inboundOrderMapper.selectInboundOrderList(inboundOrder);
            InboundOrder order = inboundOrders.get(0);
            details = inboundOrderDetailsMapper.selectInboundOrderDetailsByOrderId(order.getId());


            for (PurchaseOrderDetails detail : purchaseOrderDetails) {
                inventory.setWarehouseId(details.getWarehouseId());
                //inventory.setCategory();
                inventory.setGoodsId(detail.getGoodsId());
                inventory.setInventory(String.valueOf(detail.getCount()));
                inventory.setState(1);
                inventory.setPrice(detail.getPrice());
                inventoryService.save(inventory);
            }

            purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);

        }

        AjaxResult result = accountService.getInfo(cgreturnOrder.getPid());
        Object o = result.get(AjaxResult.DATA_TAG);
        String s = JSONObject.toJSONString(o);
        //账号
        Account account = JSONObject.parseObject(s, Account.class);
        //退款
        //account.setCurrentBalance(account.getCurrentBalance().add(details.getPayPrice()));
        account.setCurrentBalance(account.getCurrentBalance().add(cgreturnOrder.getRelPay()));
        accountService.edit(account);

        //生成订单
        CgreturnPay pay = new CgreturnPay();
        pay.setAccountId(cgreturnOrder.getPid());
        pay.setCreatedate(new Date());
        pay.setInboundOrderId(cgreturnOrder.getId());
        pay.setNote("退款支付单");
        pay.setPrice(details.getPayPrice());
        pay.setOrderno(cgreturnOrder.getOrderNo());
        cgreturnPayMapper.insertCgreturnPay(pay);

        return cgreturnOrderMapper.updateCgreturnOrder(cgreturnOrder);
    }
}
